<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" lang="" xml:lang="">
  <head>
    <meta charset="utf-8" />
    <meta name="generator" content="pandoc" />
    <meta
      name="viewport"
      content="width=device-width, initial-scale=1.0, user-scalable=yes"
    />
    <title>inputoutput</title>
    <style type="text/css">
      code {
        white-space: pre-wrap;
      }
      span.smallcaps {
        font-variant: small-caps;
      }
      span.underline {
        text-decoration: underline;
      }
      div.column {
        display: inline-block;
        vertical-align: top;
        width: 50%;
      }
    </style>
  </head>
  <body>
    <h3 id="navigation">Navigation</h3>
    <ul>
      <li>
        <a href="https://docs.python.org/3/genindex.html" title="General Index"
          >index</a
        >
      </li>
      <li>
        <a
          href="https://docs.python.org/3/py-modindex.html"
          title="Python Module Index"
          >modules</a
        >
        |
      </li>
      <li><a href="errors.html" title="8. Errors and Exceptions">next</a> |</li>
      <li><a href="modules.html" title="6. Modules">previous</a> |</li>
      <li><img src="../_static/py.png" /></li>
      <li><a href="https://www.python.org/">Python</a> »</li>
      <li>
        <a href="https://docs.python.org/3/index.html">3.9.5 Documentation</a> »
      </li>
      <li><a href="index.html">The Python Tutorial</a> »</li>
      <li><div class="line-block"></div></li>
    </ul>
    <p><span id="tut-io"></span></p>
    <h1 id="input-and-output">
      <span class="section-number">7. </span>Input and Output<a
        href="#input-and-output"
        class="headerlink"
        title="Permalink to this headline"
        >¶</a
      >
    </h1>
    <p>
      There are several ways to present the output of a program; data can be
      printed in a human-readable form, or written to a file for future use.
      This chapter will discuss some of the possibilities.
    </p>
    <p><span id="tut-formatting"></span></p>
    <h2 id="fancier-output-formatting">
      <span class="section-number">7.1. </span>Fancier Output Formatting<a
        href="#fancier-output-formatting"
        class="headerlink"
        title="Permalink to this headline"
        >¶</a
      >
    </h2>
    <p>
      So far we’ve encountered two ways of writing values:
      <em>expression statements</em> and the
      <a
        href="https://docs.python.org/3/library/functions.html#print"
        class="reference internal"
        title="print"
        ><code class="sourceCode python"
          ><span class="bu">print</span>()</code
        ></a
      >
      function. (A third way is using the <code>write()</code> method of file
      objects; the standard output file can be referenced as
      <code>sys.stdout</code>. See the Library Reference for more information on
      this.)
    </p>
    <p>
      Often you’ll want more control over the formatting of your output than
      simply printing space-separated values. There are several ways to format
      output.
    </p>
    <ul>
      <li>
        <p>
          To use
          <a href="#tut-f-strings" class="reference internal"
            ><span class="std std-ref">formatted string literals</span></a
          >, begin a string with <code>f</code> or <code>F</code> before the
          opening quotation mark or triple quotation mark. Inside this string,
          you can write a Python expression between <code>{</code> and
          <code>}</code> characters that can refer to variables or literal
          values.
        </p>
        <pre><code>&gt;&gt;&gt; year = 2016
&gt;&gt;&gt; event = &#39;Referendum&#39;
&gt;&gt;&gt; f&#39;Results of the {year} {event}&#39;
&#39;Results of the 2016 Referendum&#39;</code></pre>
      </li>
      <li>
        <p>
          The
          <a
            href="https://docs.python.org/3/library/stdtypes.html#str.format"
            class="reference internal"
            title="str.format"
            ><code class="sourceCode python"
              ><span class="bu">str</span>.<span class="bu">format</span
              >()</code
            ></a
          >
          method of strings requires more manual effort. You’ll still use
          <code>{</code> and <code>}</code> to mark where a variable will be
          substituted and can provide detailed formatting directives, but you’ll
          also need to provide the information to be formatted.
        </p>
        <pre><code>&gt;&gt;&gt; yes_votes = 42_572_654
&gt;&gt;&gt; no_votes = 43_132_495
&gt;&gt;&gt; percentage = yes_votes / (yes_votes + no_votes)
&gt;&gt;&gt; &#39;{:-9} YES votes  {:2.2%}&#39;.format(yes_votes, percentage)
&#39; 42572654 YES votes  49.67%&#39;</code></pre>
      </li>
      <li>
        <p>
          Finally, you can do all the string handling yourself by using string
          slicing and concatenation operations to create any layout you can
          imagine. The string type has some methods that perform useful
          operations for padding strings to a given column width.
        </p>
      </li>
    </ul>
    <p>
      When you don’t need fancy output but just want a quick display of some
      variables for debugging purposes, you can convert any value to a string
      with the
      <a
        href="https://docs.python.org/3/library/functions.html#repr"
        class="reference internal"
        title="repr"
        ><code class="sourceCode python"
          ><span class="bu">repr</span>()</code
        ></a
      >
      or
      <a
        href="https://docs.python.org/3/library/stdtypes.html#str"
        class="reference internal"
        title="str"
        ><code class="sourceCode python"><span class="bu">str</span>()</code></a
      >
      functions.
    </p>
    <p>
      The
      <a
        href="https://docs.python.org/3/library/stdtypes.html#str"
        class="reference internal"
        title="str"
        ><code class="sourceCode python"><span class="bu">str</span>()</code></a
      >
      function is meant to return representations of values which are fairly
      human-readable, while
      <a
        href="https://docs.python.org/3/library/functions.html#repr"
        class="reference internal"
        title="repr"
        ><code class="sourceCode python"
          ><span class="bu">repr</span>()</code
        ></a
      >
      is meant to generate representations which can be read by the interpreter
      (or will force a
      <a
        href="https://docs.python.org/3/library/exceptions.html#SyntaxError"
        class="reference internal"
        title="SyntaxError"
        ><code class="sourceCode python"
          ><span class="pp">SyntaxError</span></code
        ></a
      >
      if there is no equivalent syntax). For objects which don’t have a
      particular representation for human consumption,
      <a
        href="https://docs.python.org/3/library/stdtypes.html#str"
        class="reference internal"
        title="str"
        ><code class="sourceCode python"><span class="bu">str</span>()</code></a
      >
      will return the same value as
      <a
        href="https://docs.python.org/3/library/functions.html#repr"
        class="reference internal"
        title="repr"
        ><code class="sourceCode python"
          ><span class="bu">repr</span>()</code
        ></a
      >. Many values, such as numbers or structures like lists and dictionaries,
      have the same representation using either function. Strings, in
      particular, have two distinct representations.
    </p>
    <p>Some examples:</p>
    <pre><code>&gt;&gt;&gt; s = &#39;Hello, world.&#39;
&gt;&gt;&gt; str(s)
&#39;Hello, world.&#39;
&gt;&gt;&gt; repr(s)
&quot;&#39;Hello, world.&#39;&quot;
&gt;&gt;&gt; str(1/7)
&#39;0.14285714285714285&#39;
&gt;&gt;&gt; x = 10 * 3.25
&gt;&gt;&gt; y = 200 * 200
&gt;&gt;&gt; s = &#39;The value of x is &#39; + repr(x) + &#39;, and y is &#39; + repr(y) + &#39;...&#39;
&gt;&gt;&gt; print(s)
The value of x is 32.5, and y is 40000...
&gt;&gt;&gt; # The repr() of a string adds string quotes and backslashes:
... hello = &#39;hello, world\n&#39;
&gt;&gt;&gt; hellos = repr(hello)
&gt;&gt;&gt; print(hellos)
&#39;hello, world\n&#39;
&gt;&gt;&gt; # The argument to repr() may be any Python object:
... repr((x, y, (&#39;spam&#39;, &#39;eggs&#39;)))
&quot;(32.5, 40000, (&#39;spam&#39;, &#39;eggs&#39;))&quot;</code></pre>
    <p>
      The
      <a
        href="https://docs.python.org/3/library/string.html#module-string"
        class="reference internal"
        title="string: Common string operations."
        ><code class="sourceCode python">string</code></a
      >
      module contains a
      <a
        href="https://docs.python.org/3/library/string.html#string.Template"
        class="reference internal"
        title="string.Template"
        ><code class="sourceCode python">Template</code></a
      >
      class that offers yet another way to substitute values into strings, using
      placeholders like <code>$x</code> and replacing them with values from a
      dictionary, but offers much less control of the formatting.
    </p>
    <p><span id="tut-f-strings"></span></p>
    <h3 id="formatted-string-literals">
      <span class="section-number">7.1.1. </span>Formatted String Literals<a
        href="#formatted-string-literals"
        class="headerlink"
        title="Permalink to this headline"
        >¶</a
      >
    </h3>
    <p>
      <a
        href="https://docs.python.org/3/reference/lexical_analysis.html#f-strings"
        class="reference internal"
        ><span class="std std-ref">Formatted string literals</span></a
      >
      (also called f-strings for short) let you include the value of Python
      expressions inside a string by prefixing the string with <code>f</code> or
      <code>F</code> and writing expressions as <code>{expression}</code>.
    </p>
    <p>
      An optional format specifier can follow the expression. This allows
      greater control over how the value is formatted. The following example
      rounds pi to three places after the decimal:
    </p>
    <pre><code>&gt;&gt;&gt; import math
&gt;&gt;&gt; print(f&#39;The value of pi is approximately {math.pi:.3f}.&#39;)
The value of pi is approximately 3.142.</code></pre>
    <p>
      Passing an integer after the <code>':'</code> will cause that field to be
      a minimum number of characters wide. This is useful for making columns
      line up.
    </p>
    <pre><code>&gt;&gt;&gt; table = {&#39;Sjoerd&#39;: 4127, &#39;Jack&#39;: 4098, &#39;Dcab&#39;: 7678}
&gt;&gt;&gt; for name, phone in table.items():
...     print(f&#39;{name:10} ==&gt; {phone:10d}&#39;)
...
Sjoerd     ==&gt;       4127
Jack       ==&gt;       4098
Dcab       ==&gt;       7678</code></pre>
    <p>
      Other modifiers can be used to convert the value before it is formatted.
      <code>'!a'</code> applies
      <a
        href="https://docs.python.org/3/library/functions.html#ascii"
        class="reference internal"
        title="ascii"
        ><code class="sourceCode python"
          ><span class="bu">ascii</span>()</code
        ></a
      >, <code>'!s'</code> applies
      <a
        href="https://docs.python.org/3/library/stdtypes.html#str"
        class="reference internal"
        title="str"
        ><code class="sourceCode python"><span class="bu">str</span>()</code></a
      >, and <code>'!r'</code> applies
      <a
        href="https://docs.python.org/3/library/functions.html#repr"
        class="reference internal"
        title="repr"
        ><code class="sourceCode python"
          ><span class="bu">repr</span>()</code
        ></a
      >:
    </p>
    <pre><code>&gt;&gt;&gt; animals = &#39;eels&#39;
&gt;&gt;&gt; print(f&#39;My hovercraft is full of {animals}.&#39;)
My hovercraft is full of eels.
&gt;&gt;&gt; print(f&#39;My hovercraft is full of {animals!r}.&#39;)
My hovercraft is full of &#39;eels&#39;.</code></pre>
    <p>
      For a reference on these format specifications, see the reference guide
      for the
      <a
        href="https://docs.python.org/3/library/string.html#formatspec"
        class="reference internal"
        ><span class="std std-ref">Format Specification Mini-Language</span></a
      >.
    </p>
    <p><span id="tut-string-format"></span></p>
    <h3 id="the-string-format-method">
      <span class="section-number">7.1.2. </span>The String format() Method<a
        href="#the-string-format-method"
        class="headerlink"
        title="Permalink to this headline"
        >¶</a
      >
    </h3>
    <p>
      Basic usage of the
      <a
        href="https://docs.python.org/3/library/stdtypes.html#str.format"
        class="reference internal"
        title="str.format"
        ><code class="sourceCode python"
          ><span class="bu">str</span>.<span class="bu">format</span>()</code
        ></a
      >
      method looks like this:
    </p>
    <pre><code>&gt;&gt;&gt; print(&#39;We are the {} who say &quot;{}!&quot;&#39;.format(&#39;knights&#39;, &#39;Ni&#39;))
We are the knights who say &quot;Ni!&quot;</code></pre>
    <p>
      The brackets and characters within them (called format fields) are
      replaced with the objects passed into the
      <a
        href="https://docs.python.org/3/library/stdtypes.html#str.format"
        class="reference internal"
        title="str.format"
        ><code class="sourceCode python"
          ><span class="bu">str</span>.<span class="bu">format</span>()</code
        ></a
      >
      method. A number in the brackets can be used to refer to the position of
      the object passed into the
      <a
        href="https://docs.python.org/3/library/stdtypes.html#str.format"
        class="reference internal"
        title="str.format"
        ><code class="sourceCode python"
          ><span class="bu">str</span>.<span class="bu">format</span>()</code
        ></a
      >
      method.
    </p>
    <pre><code>&gt;&gt;&gt; print(&#39;{0} and {1}&#39;.format(&#39;spam&#39;, &#39;eggs&#39;))
spam and eggs
&gt;&gt;&gt; print(&#39;{1} and {0}&#39;.format(&#39;spam&#39;, &#39;eggs&#39;))
eggs and spam</code></pre>
    <p>
      If keyword arguments are used in the
      <a
        href="https://docs.python.org/3/library/stdtypes.html#str.format"
        class="reference internal"
        title="str.format"
        ><code class="sourceCode python"
          ><span class="bu">str</span>.<span class="bu">format</span>()</code
        ></a
      >
      method, their values are referred to by using the name of the argument.
    </p>
    <pre><code>&gt;&gt;&gt; print(&#39;This {food} is {adjective}.&#39;.format(
...       food=&#39;spam&#39;, adjective=&#39;absolutely horrible&#39;))
This spam is absolutely horrible.</code></pre>
    <p>Positional and keyword arguments can be arbitrarily combined:</p>
    <pre><code>&gt;&gt;&gt; print(&#39;The story of {0}, {1}, and {other}.&#39;.format(&#39;Bill&#39;, &#39;Manfred&#39;,
                                                       other=&#39;Georg&#39;))
The story of Bill, Manfred, and Georg.</code></pre>
    <p>
      If you have a really long format string that you don’t want to split up,
      it would be nice if you could reference the variables to be formatted by
      name instead of by position. This can be done by simply passing the dict
      and using square brackets <code>'[]'</code> to access the keys.
    </p>
    <pre><code>&gt;&gt;&gt; table = {&#39;Sjoerd&#39;: 4127, &#39;Jack&#39;: 4098, &#39;Dcab&#39;: 8637678}
&gt;&gt;&gt; print(&#39;Jack: {0[Jack]:d}; Sjoerd: {0[Sjoerd]:d}; &#39;
...       &#39;Dcab: {0[Dcab]:d}&#39;.format(table))
Jack: 4098; Sjoerd: 4127; Dcab: 8637678</code></pre>
    <p>
      This could also be done by passing the table as keyword arguments with the
      ‘**’ notation.
    </p>
    <pre><code>&gt;&gt;&gt; table = {&#39;Sjoerd&#39;: 4127, &#39;Jack&#39;: 4098, &#39;Dcab&#39;: 8637678}
&gt;&gt;&gt; print(&#39;Jack: {Jack:d}; Sjoerd: {Sjoerd:d}; Dcab: {Dcab:d}&#39;.format(**table))
Jack: 4098; Sjoerd: 4127; Dcab: 8637678</code></pre>
    <p>
      This is particularly useful in combination with the built-in function
      <a
        href="https://docs.python.org/3/library/functions.html#vars"
        class="reference internal"
        title="vars"
        ><code class="sourceCode python"
          ><span class="bu">vars</span>()</code
        ></a
      >, which returns a dictionary containing all local variables.
    </p>
    <p>
      As an example, the following lines produce a tidily-aligned set of columns
      giving integers and their squares and cubes:
    </p>
    <pre><code>&gt;&gt;&gt; for x in range(1, 11):
...     print(&#39;{0:2d} {1:3d} {2:4d}&#39;.format(x, x*x, x*x*x))
...
 1   1    1
 2   4    8
 3   9   27
 4  16   64
 5  25  125
 6  36  216
 7  49  343
 8  64  512
 9  81  729
10 100 1000</code></pre>
    <p>
      For a complete overview of string formatting with
      <a
        href="https://docs.python.org/3/library/stdtypes.html#str.format"
        class="reference internal"
        title="str.format"
        ><code class="sourceCode python"
          ><span class="bu">str</span>.<span class="bu">format</span>()</code
        ></a
      >, see
      <a
        href="https://docs.python.org/3/library/string.html#formatstrings"
        class="reference internal"
        ><span class="std std-ref">Format String Syntax</span></a
      >.
    </p>
    <h3 id="manual-string-formatting">
      <span class="section-number">7.1.3. </span>Manual String Formatting<a
        href="#manual-string-formatting"
        class="headerlink"
        title="Permalink to this headline"
        >¶</a
      >
    </h3>
    <p>Here’s the same table of squares and cubes, formatted manually:</p>
    <pre><code>&gt;&gt;&gt; for x in range(1, 11):
...     print(repr(x).rjust(2), repr(x*x).rjust(3), end=&#39; &#39;)
...     # Note use of &#39;end&#39; on previous line
...     print(repr(x*x*x).rjust(4))
...
 1   1    1
 2   4    8
 3   9   27
 4  16   64
 5  25  125
 6  36  216
 7  49  343
 8  64  512
 9  81  729
10 100 1000</code></pre>
    <p>
      (Note that the one space between each column was added by the way
      <a
        href="https://docs.python.org/3/library/functions.html#print"
        class="reference internal"
        title="print"
        ><code class="sourceCode python"
          ><span class="bu">print</span>()</code
        ></a
      >
      works: it always adds spaces between its arguments.)
    </p>
    <p>
      The
      <a
        href="https://docs.python.org/3/library/stdtypes.html#str.rjust"
        class="reference internal"
        title="str.rjust"
        ><code class="sourceCode python"
          ><span class="bu">str</span>.rjust()</code
        ></a
      >
      method of string objects right-justifies a string in a field of a given
      width by padding it with spaces on the left. There are similar methods
      <a
        href="https://docs.python.org/3/library/stdtypes.html#str.ljust"
        class="reference internal"
        title="str.ljust"
        ><code class="sourceCode python"
          ><span class="bu">str</span>.ljust()</code
        ></a
      >
      and
      <a
        href="https://docs.python.org/3/library/stdtypes.html#str.center"
        class="reference internal"
        title="str.center"
        ><code class="sourceCode python"
          ><span class="bu">str</span>.center()</code
        ></a
      >. These methods do not write anything, they just return a new string. If
      the input string is too long, they don’t truncate it, but return it
      unchanged; this will mess up your column lay-out but that’s usually better
      than the alternative, which would be lying about a value. (If you really
      want truncation you can always add a slice operation, as in
      <code>x.ljust(n)[:n]</code>.)
    </p>
    <p>
      There is another method,
      <a
        href="https://docs.python.org/3/library/stdtypes.html#str.zfill"
        class="reference internal"
        title="str.zfill"
        ><code class="sourceCode python"
          ><span class="bu">str</span>.zfill()</code
        ></a
      >, which pads a numeric string on the left with zeros. It understands
      about plus and minus signs:
    </p>
    <pre><code>&gt;&gt;&gt; &#39;12&#39;.zfill(5)
&#39;00012&#39;
&gt;&gt;&gt; &#39;-3.14&#39;.zfill(7)
&#39;-003.14&#39;
&gt;&gt;&gt; &#39;3.14159265359&#39;.zfill(5)
&#39;3.14159265359&#39;</code></pre>
    <h3 id="old-string-formatting">
      <span class="section-number">7.1.4. </span>Old string formatting<a
        href="#old-string-formatting"
        class="headerlink"
        title="Permalink to this headline"
        >¶</a
      >
    </h3>
    <p>
      The % operator (modulo) can also be used for string formatting. Given
      <code>'string' % values</code>, instances of <code>%</code> in
      <code>string</code> are replaced with zero or more elements of
      <code>values</code>. This operation is commonly known as string
      interpolation. For example:
    </p>
    <pre><code>&gt;&gt;&gt; import math
&gt;&gt;&gt; print(&#39;The value of pi is approximately %5.3f.&#39; % math.pi)
The value of pi is approximately 3.142.</code></pre>
    <p>
      More information can be found in the
      <a
        href="https://docs.python.org/3/library/stdtypes.html#old-string-formatting"
        class="reference internal"
        ><span class="std std-ref">printf-style String Formatting</span></a
      >
      section.
    </p>
    <p><span id="tut-files"></span></p>
    <h2 id="reading-and-writing-files">
      <span class="section-number">7.2. </span>Reading and Writing Files<a
        href="#reading-and-writing-files"
        class="headerlink"
        title="Permalink to this headline"
        >¶</a
      >
    </h2>
    <p>
      <a
        href="https://docs.python.org/3/library/functions.html#open"
        class="reference internal"
        title="open"
        ><code class="sourceCode python"
          ><span class="bu">open</span>()</code
        ></a
      >
      returns a
      <a
        href="https://docs.python.org/3/glossary.html#term-file-object"
        class="reference internal"
        ><span class="xref std std-term">file object</span></a
      >, and is most commonly used with two arguments:
      <code>open(filename, mode)</code>.
    </p>
    <pre><code>&gt;&gt;&gt; f = open(&#39;workfile&#39;, &#39;w&#39;)</code></pre>
    <p>
      The first argument is a string containing the filename. The second
      argument is another string containing a few characters describing the way
      in which the file will be used. <em>mode</em> can be <code>'r'</code> when
      the file will only be read, <code>'w'</code> for only writing (an existing
      file with the same name will be erased), and <code>'a'</code> opens the
      file for appending; any data written to the file is automatically added to
      the end. <code>'r+'</code> opens the file for both reading and writing.
      The <em>mode</em> argument is optional; <code>'r'</code> will be assumed
      if it’s omitted.
    </p>
    <p>
      Normally, files are opened in <em>text mode</em>, that means, you read and
      write strings from and to the file, which are encoded in a specific
      encoding. If encoding is not specified, the default is platform dependent
      (see
      <a
        href="https://docs.python.org/3/library/functions.html#open"
        class="reference internal"
        title="open"
        ><code class="sourceCode python"
          ><span class="bu">open</span>()</code
        ></a
      >). <code>'b'</code> appended to the mode opens the file in
      <em>binary mode</em>: now the data is read and written in the form of
      bytes objects. This mode should be used for all files that don’t contain
      text.
    </p>
    <p>
      In text mode, the default when reading is to convert platform-specific
      line endings (<code>\n</code> on Unix, <code>\r\n</code> on Windows) to
      just <code>\n</code>. When writing in text mode, the default is to convert
      occurrences of <code>\n</code> back to platform-specific line endings.
      This behind-the-scenes modification to file data is fine for text files,
      but will corrupt binary data like that in <code>JPEG</code> or
      <code>EXE</code> files. Be very careful to use binary mode when reading
      and writing such files.
    </p>
    <p>
      It is good practice to use the
      <a
        href="https://docs.python.org/3/reference/compound_stmts.html#with"
        class="reference internal"
        ><code class="xref std std-keyword docutils literal notranslate"
          >with</code
        ></a
      >
      keyword when dealing with file objects. The advantage is that the file is
      properly closed after its suite finishes, even if an exception is raised
      at some point. Using <code>with</code> is also much shorter than writing
      equivalent
      <a
        href="https://docs.python.org/3/reference/compound_stmts.html#try"
        class="reference internal"
        ><code class="xref std std-keyword docutils literal notranslate"
          >try</code
        ></a
      >-<a
        href="https://docs.python.org/3/reference/compound_stmts.html#finally"
        class="reference internal"
        ><code class="xref std std-keyword docutils literal notranslate"
          >finally</code
        ></a
      >
      blocks:
    </p>
    <pre><code>&gt;&gt;&gt; with open(&#39;workfile&#39;) as f:
...     read_data = f.read()

&gt;&gt;&gt; # We can check that the file has been automatically closed.
&gt;&gt;&gt; f.closed
True</code></pre>
    <p>
      If you’re not using the
      <a
        href="https://docs.python.org/3/reference/compound_stmts.html#with"
        class="reference internal"
        ><code class="xref std std-keyword docutils literal notranslate"
          >with</code
        ></a
      >
      keyword, then you should call <code>f.close()</code> to close the file and
      immediately free up any system resources used by it.
    </p>
    <p>Warning</p>
    <p>
      Calling <code>f.write()</code> without using the <code>with</code> keyword
      or calling <code>f.close()</code> <strong>might</strong> result in the
      arguments of <code>f.write()</code> not being completely written to the
      disk, even if the program exits successfully.
    </p>
    <p>
      After a file object is closed, either by a
      <a
        href="https://docs.python.org/3/reference/compound_stmts.html#with"
        class="reference internal"
        ><code class="xref std std-keyword docutils literal notranslate"
          >with</code
        ></a
      >
      statement or by calling <code>f.close()</code>, attempts to use the file
      object will automatically fail.
    </p>
    <pre><code>&gt;&gt;&gt; f.close()
&gt;&gt;&gt; f.read()
Traceback (most recent call last):
  File &quot;&lt;stdin&gt;&quot;, line 1, in &lt;module&gt;
ValueError: I/O operation on closed file.</code></pre>
    <p><span id="tut-filemethods"></span></p>
    <h3 id="methods-of-file-objects">
      <span class="section-number">7.2.1. </span>Methods of File Objects<a
        href="#methods-of-file-objects"
        class="headerlink"
        title="Permalink to this headline"
        >¶</a
      >
    </h3>
    <p>
      The rest of the examples in this section will assume that a file object
      called <code>f</code> has already been created.
    </p>
    <p>
      To read a file’s contents, call <code>f.read(size)</code>, which reads
      some quantity of data and returns it as a string (in text mode) or bytes
      object (in binary mode). <em>size</em> is an optional numeric argument.
      When <em>size</em> is omitted or negative, the entire contents of the file
      will be read and returned; it’s your problem if the file is twice as large
      as your machine’s memory. Otherwise, at most <em>size</em> characters (in
      text mode) or <em>size</em> bytes (in binary mode) are read and returned.
      If the end of the file has been reached, <code>f.read()</code> will return
      an empty string (<code>''</code>).
    </p>
    <pre><code>&gt;&gt;&gt; f.read()
&#39;This is the entire file.\n&#39;
&gt;&gt;&gt; f.read()
&#39;&#39;</code></pre>
    <p>
      <code>f.readline()</code> reads a single line from the file; a newline
      character (<code>\n</code>) is left at the end of the string, and is only
      omitted on the last line of the file if the file doesn’t end in a newline.
      This makes the return value unambiguous; if
      <code>f.readline()</code> returns an empty string, the end of the file has
      been reached, while a blank line is represented by <code>'\n'</code>, a
      string containing only a single newline.
    </p>
    <pre><code>&gt;&gt;&gt; f.readline()
&#39;This is the first line of the file.\n&#39;
&gt;&gt;&gt; f.readline()
&#39;Second line of the file\n&#39;
&gt;&gt;&gt; f.readline()
&#39;&#39;</code></pre>
    <p>
      For reading lines from a file, you can loop over the file object. This is
      memory efficient, fast, and leads to simple code:
    </p>
    <pre><code>&gt;&gt;&gt; for line in f:
...     print(line, end=&#39;&#39;)
...
This is the first line of the file.
Second line of the file</code></pre>
    <p>
      If you want to read all the lines of a file in a list you can also use
      <code>list(f)</code> or <code>f.readlines()</code>.
    </p>
    <p>
      <code>f.write(string)</code> writes the contents of <em>string</em> to the
      file, returning the number of characters written.
    </p>
    <pre><code>&gt;&gt;&gt; f.write(&#39;This is a test\n&#39;)
15</code></pre>
    <p>
      Other types of objects need to be converted – either to a string (in text
      mode) or a bytes object (in binary mode) – before writing them:
    </p>
    <pre><code>&gt;&gt;&gt; value = (&#39;the answer&#39;, 42)
&gt;&gt;&gt; s = str(value)  # convert the tuple to string
&gt;&gt;&gt; f.write(s)
18</code></pre>
    <p>
      <code>f.tell()</code> returns an integer giving the file object’s current
      position in the file represented as number of bytes from the beginning of
      the file when in binary mode and an opaque number when in text mode.
    </p>
    <p>
      To change the file object’s position, use
      <code>f.seek(offset, whence)</code>. The position is computed from adding
      <em>offset</em> to a reference point; the reference point is selected by
      the <em>whence</em> argument. A <em>whence</em> value of 0 measures from
      the beginning of the file, 1 uses the current file position, and 2 uses
      the end of the file as the reference point. <em>whence</em> can be omitted
      and defaults to 0, using the beginning of the file as the reference point.
    </p>
    <pre><code>&gt;&gt;&gt; f = open(&#39;workfile&#39;, &#39;rb+&#39;)
&gt;&gt;&gt; f.write(b&#39;0123456789abcdef&#39;)
16
&gt;&gt;&gt; f.seek(5)      # Go to the 6th byte in the file
5
&gt;&gt;&gt; f.read(1)
b&#39;5&#39;
&gt;&gt;&gt; f.seek(-3, 2)  # Go to the 3rd byte before the end
13
&gt;&gt;&gt; f.read(1)
b&#39;d&#39;</code></pre>
    <p>
      In text files (those opened without a <code>b</code> in the mode string),
      only seeks relative to the beginning of the file are allowed (the
      exception being seeking to the very file end with <code>seek(0, 2)</code>)
      and the only valid <em>offset</em> values are those returned from the
      <code>f.tell()</code>, or zero. Any other <em>offset</em> value produces
      undefined behaviour.
    </p>
    <p>
      File objects have some additional methods, such as
      <code>isatty()</code> and <code>truncate()</code> which are less
      frequently used; consult the Library Reference for a complete guide to
      file objects.
    </p>
    <p><span id="tut-json"></span></p>
    <h3 id="saving-structured-data-with-json">
      <span class="section-number">7.2.2. </span>Saving structured data with
      <a
        href="https://docs.python.org/3/library/json.html#module-json"
        class="reference internal"
        title="json: Encode and decode the JSON format."
        ><code class="sourceCode python">json</code></a
      ><a
        href="#saving-structured-data-with-json"
        class="headerlink"
        title="Permalink to this headline"
        >¶</a
      >
    </h3>
    <p>
      Strings can easily be written to and read from a file. Numbers take a bit
      more effort, since the <code>read()</code> method only returns strings,
      which will have to be passed to a function like
      <a
        href="https://docs.python.org/3/library/functions.html#int"
        class="reference internal"
        title="int"
        ><code class="sourceCode python"><span class="bu">int</span>()</code></a
      >, which takes a string like <code>'123'</code> and returns its numeric
      value 123. When you want to save more complex data types like nested lists
      and dictionaries, parsing and serializing by hand becomes complicated.
    </p>
    <p>
      Rather than having users constantly writing and debugging code to save
      complicated data types to files, Python allows you to use the popular data
      interchange format called
      <a href="http://json.org/" class="reference external"
        >JSON (JavaScript Object Notation)</a
      >. The standard module called
      <a
        href="https://docs.python.org/3/library/json.html#module-json"
        class="reference internal"
        title="json: Encode and decode the JSON format."
        ><code class="sourceCode python">json</code></a
      >
      can take Python data hierarchies, and convert them to string
      representations; this process is called <em>serializing</em>.
      Reconstructing the data from the string representation is called
      <em>deserializing</em>. Between serializing and deserializing, the string
      representing the object may have been stored in a file or data, or sent
      over a network connection to some distant machine.
    </p>
    <p>Note</p>
    <p>
      The JSON format is commonly used by modern applications to allow for data
      exchange. Many programmers are already familiar with it, which makes it a
      good choice for interoperability.
    </p>
    <p>
      If you have an object <code>x</code>, you can view its JSON string
      representation with a simple line of code:
    </p>
    <pre><code>&gt;&gt;&gt; import json
&gt;&gt;&gt; x = [1, &#39;simple&#39;, &#39;list&#39;]
&gt;&gt;&gt; json.dumps(x)
&#39;[1, &quot;simple&quot;, &quot;list&quot;]&#39;</code></pre>
    <p>
      Another variant of the
      <a
        href="https://docs.python.org/3/library/json.html#json.dumps"
        class="reference internal"
        title="json.dumps"
        ><code class="sourceCode python">dumps()</code></a
      >
      function, called
      <a
        href="https://docs.python.org/3/library/json.html#json.dump"
        class="reference internal"
        title="json.dump"
        ><code class="sourceCode python">dump()</code></a
      >, simply serializes the object to a
      <a
        href="https://docs.python.org/3/glossary.html#term-text-file"
        class="reference internal"
        ><span class="xref std std-term">text file</span></a
      >. So if <code>f</code> is a
      <a
        href="https://docs.python.org/3/glossary.html#term-text-file"
        class="reference internal"
        ><span class="xref std std-term">text file</span></a
      >
      object opened for writing, we can do this:
    </p>
    <pre><code>json.dump(x, f)</code></pre>
    <p>
      To decode the object again, if <code>f</code> is a
      <a
        href="https://docs.python.org/3/glossary.html#term-text-file"
        class="reference internal"
        ><span class="xref std std-term">text file</span></a
      >
      object which has been opened for reading:
    </p>
    <pre><code>x = json.load(f)</code></pre>
    <p>
      This simple serialization technique can handle lists and dictionaries, but
      serializing arbitrary class instances in JSON requires a bit of extra
      effort. The reference for the
      <a
        href="https://docs.python.org/3/library/json.html#module-json"
        class="reference internal"
        title="json: Encode and decode the JSON format."
        ><code class="sourceCode python">json</code></a
      >
      module contains an explanation of this.
    </p>
    <p>See also</p>
    <p>
      <a
        href="https://docs.python.org/3/library/pickle.html#module-pickle"
        class="reference internal"
        title="pickle: Convert Python objects to streams of bytes and back."
        ><code class="sourceCode python">pickle</code></a
      >
      - the pickle module
    </p>
    <p>
      Contrary to
      <a href="#tut-json" class="reference internal"
        ><span class="std std-ref">JSON</span></a
      >, <em>pickle</em> is a protocol which allows the serialization of
      arbitrarily complex Python objects. As such, it is specific to Python and
      cannot be used to communicate with applications written in other
      languages. It is also insecure by default: deserializing pickle data
      coming from an untrusted source can execute arbitrary code, if the data
      was crafted by a skilled attacker.
    </p>
    <h3 id="table-of-contents">
      <a href="https://docs.python.org/3/contents.html">Table of Contents</a>
    </h3>
    <ul>
      <li>
        <a href="#" class="reference internal">7. Input and Output</a>
        <ul>
          <li>
            <a href="#fancier-output-formatting" class="reference internal"
              >7.1. Fancier Output Formatting</a
            >
            <ul>
              <li>
                <a href="#formatted-string-literals" class="reference internal"
                  >7.1.1. Formatted String Literals</a
                >
              </li>
              <li>
                <a href="#the-string-format-method" class="reference internal"
                  >7.1.2. The String format() Method</a
                >
              </li>
              <li>
                <a href="#manual-string-formatting" class="reference internal"
                  >7.1.3. Manual String Formatting</a
                >
              </li>
              <li>
                <a href="#old-string-formatting" class="reference internal"
                  >7.1.4. Old string formatting</a
                >
              </li>
            </ul>
          </li>
          <li>
            <a href="#reading-and-writing-files" class="reference internal"
              >7.2. Reading and Writing Files</a
            >
            <ul>
              <li>
                <a href="#methods-of-file-objects" class="reference internal"
                  >7.2.1. Methods of File Objects</a
                >
              </li>
              <li>
                <a
                  href="#saving-structured-data-with-json"
                  class="reference internal"
                  >7.2.2. Saving structured data with
                  <code class="sourceCode python">json</code></a
                >
              </li>
            </ul>
          </li>
        </ul>
      </li>
    </ul>
    <h4 id="previous-topic">Previous topic</h4>
    <p>
      <a href="modules.html" title="previous chapter"
        ><span class="section-number">6. </span>Modules</a
      >
    </p>
    <h4 id="next-topic">Next topic</h4>
    <p>
      <a href="errors.html" title="next chapter"
        ><span class="section-number">8. </span>Errors and Exceptions</a
      >
    </p>
    <h3 id="this-page">This Page</h3>
    <ul>
      <li><a href="https://docs.python.org/3/bugs.html">Report a Bug</a></li>
      <li>
        <a
          href="https://github.com/python/cpython/blob/3.9/Doc/tutorial/inputoutput.rst"
          >Show Source</a
        >
      </li>
    </ul>
    <h3 id="navigation-1">Navigation</h3>
    <ul>
      <li>
        <a href="https://docs.python.org/3/genindex.html" title="General Index"
          >index</a
        >
      </li>
      <li>
        <a
          href="https://docs.python.org/3/py-modindex.html"
          title="Python Module Index"
          >modules</a
        >
        |
      </li>
      <li><a href="errors.html" title="8. Errors and Exceptions">next</a> |</li>
      <li><a href="modules.html" title="6. Modules">previous</a> |</li>
      <li><img src="../_static/py.png" /></li>
      <li><a href="https://www.python.org/">Python</a> »</li>
      <li>
        <a href="https://docs.python.org/3/index.html">3.9.5 Documentation</a> »
      </li>
      <li><a href="index.html">The Python Tutorial</a> »</li>
      <li><div class="line-block"></div></li>
    </ul>
    <p>
      ©
      <a href="https://docs.python.org/3/copyright.html">Copyright</a>
      2001-2021, Python Software Foundation.<br />
      The Python Software Foundation is a non-profit corporation.
      <a href="https://www.python.org/psf/donations/">Please donate.</a>
    </p>
    <p>
      Last updated on May 30, 2021.
      <a href="https://docs.python.org/3/bugs.html">Found a bug</a>?<br />
      Created using <a href="https://www.sphinx-doc.org/">Sphinx</a> 2.4.4.
    </p>
  </body>
</html>
